package com.zonesion.robot.ai.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.king.anetty.ANetty;
import com.king.anetty.Netty;
import com.kongqw.rockerlibrary.view.RockerView;
import com.warkiz.widget.IndicatorSeekBar;
import com.warkiz.widget.OnSeekChangeListener;
import com.warkiz.widget.SeekParams;
import com.zonesion.robot.ai.R;
import com.zonesion.robot.ai.common.Constants;
import com.zonesion.robot.ai.wifi.util.WifiUtils;

import io.netty.channel.ChannelHandlerContext;

public class MainActivity extends PermissionsActivity implements View.OnClickListener {

  private static final String TAG = "MainActivity";

  private Toast mToast;

  //TODO 配置您的TCP连接主机
  private String mHost = "192.168.100.253";
  private int mPort = 92;

  private Netty mNetty;
  private TextView wifimTV;
  //    private ImageButton wifi;
  private TextView mTV0, mTV1, mTV2, mTV4, mTV5, mTV6, mTV7;
  private TextView mTVRadar1, mTVRadar2, mTVRadar3, mTVRadar4;

  private ImageButton igb_wifi, btn_check, btn_grasp, btn_release, btn_whistle;
  private TextView mSpeedTV;
  private TextView mSettingTV;
  private IndicatorSeekBar listener;
  private TextView tvTle;
  private TextView tvRot;
  private IndicatorSeekBar tleSeekbar;
  private IndicatorSeekBar rotSeekbar;
  private TextView xTV, yTV, zTV;
  private IndicatorSeekBar xSeekbar;
  private IndicatorSeekBar ySeekbar;
  private IndicatorSeekBar zSeekbar;

  private Button mBtnModeControl, mBtnModeTrack, mBtnModeAvoidance, mBtnModeClour, mBtnModeSource, mBtnModeAuto;

  @SuppressLint("ClickableViewAccessibility")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //保持亮屏
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    wifimTV = findViewById(R.id.wifi_text);
//        wifi = (ImageButton) findViewById(R.id.wifi);
    mTV0 = findViewById(R.id.tv_ation);
    mTV1 = findViewById(R.id.tv_smoke);
    mTV2 = findViewById(R.id.tv_air);
    mTV4 = findViewById(R.id.tv_temp);
    mTV5 = findViewById(R.id.tv_hum);
    mTV6 = findViewById(R.id.tv_press);
    mTV7 = findViewById(R.id.tv_ele);
    mTVRadar1 = findViewById(R.id.tv_radar1);
    mTVRadar2 = findViewById(R.id.tv_radar2);
    mTVRadar3 = findViewById(R.id.tv_radar3);
    mTVRadar4 = findViewById(R.id.tv_radar4);

    igb_wifi = findViewById(R.id.igb_wifi);
    btn_check = findViewById(R.id.btn_check);
    btn_grasp = findViewById(R.id.btn_grasp);
    btn_release = findViewById(R.id.btn_release);
    btn_whistle = findViewById(R.id.btn_whistle);
    mSettingTV = findViewById(R.id.tv_setting);
    mSpeedTV = findViewById(R.id.tv_speed2);
    listener = findViewById(R.id.listener);
    tleSeekbar = findViewById(R.id.tle_seekbar);
    rotSeekbar = findViewById(R.id.rot_seekbar);
    tvTle = findViewById(R.id.tv_tel);
    tvRot = findViewById(R.id.tv_rot);
    xTV = findViewById(R.id.tv_x);
    yTV = findViewById(R.id.tv_y);
    zTV = findViewById(R.id.tv_z);
    xSeekbar = findViewById(R.id.x_seekbar);
    ySeekbar = findViewById(R.id.y_seekbar);
    zSeekbar = findViewById(R.id.z_seekbar);
    RockerView rockerViewLeft = findViewById(R.id.rockerView_left);
    if (rockerViewLeft != null) {
      rockerViewLeft.setCallBackMode(RockerView.CallBackMode.CALL_BACK_MODE_STATE_CHANGE);
      rockerViewLeft.setOnShakeListener(RockerView.DirectionMode.DIRECTION_4_ROTATE_45, new RockerView.OnShakeListener() {
        @Override
        public void onStart() {
          Log.e(TAG, "===摇杆onStart");

        }

        @Override
        public void direction(RockerView.Direction direction) {
          Log.e(TAG, "===摇动方向" + getDirection(direction));

        }

        @Override
        public void onFinish() {
          Log.e(TAG, "===摇杆onFinish");
          sendNettyMsg(Constants.V4[0]);

        }
      });
    }
    btn_whistle.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
          case KeyEvent.ACTION_UP:
            btn_whistle.setBackgroundResource(R.drawable.whistle_false);
            sendNettyMsg(Constants.V7[1]);
            break;
          case KeyEvent.ACTION_DOWN:
            btn_whistle.setBackgroundResource(R.drawable.whistle_true);
            sendNettyMsg(Constants.V7[0]);
            break;
        }
        return true;
      }
    });
//        wifi.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(MainActivity.this,WIFIActivity.class));
//            }
//        });
    igb_wifi.setOnClickListener(v -> connectNetty());
    btn_check.setOnClickListener(v -> sendNettyMsg("sc\n"));
    btn_grasp.setOnClickListener(view -> sendNettyMsg(Constants.V2[2]));
    btn_release.setOnClickListener(view -> sendNettyMsg(Constants.V2[3]));
    listener.setOnSeekChangeListener(new myOnSeekChangeListener());
    tleSeekbar.setOnSeekChangeListener(new myTleSeekbar());
    rotSeekbar.setOnSeekChangeListener(new myRotSeekbar());
    xSeekbar.setOnSeekChangeListener(new myXSeekbar());
    ySeekbar.setOnSeekChangeListener(new myYSeekbar());
    zSeekbar.setOnSeekChangeListener(new myZSeekbar());
    initNetty();
    mHandler.sendEmptyMessageDelayed(0, 4000);

    mBtnModeControl = findViewById(R.id.btn_control);
    mBtnModeTrack = findViewById(R.id.btn_track);
    mBtnModeAvoidance = findViewById(R.id.btn_avoidance);
    mBtnModeClour = findViewById(R.id.btn_clour);
    mBtnModeSource = findViewById(R.id.btn_source);
    mBtnModeAuto = findViewById(R.id.btn_auto);
    mBtnModeControl.setOnClickListener(mOnModeClick);

    mBtnModeTrack.setOnClickListener(mOnModeClick);
    mBtnModeAvoidance.setOnClickListener(mOnModeClick);
    mBtnModeClour.setOnClickListener(mOnModeClick);
    mBtnModeSource.setOnClickListener(mOnModeClick);
    mBtnModeAuto.setOnClickListener(mOnModeClick);
  }

  @SuppressLint("HandlerLeak")
  Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      if (msg.what == 0) {
        if (mNetty.isConnected()) {
          mNetty.sendMessage("sensor\n");
        }
        mHandler.sendEmptyMessageDelayed(0, 4000);
      }
    }
  };

  @Override
  public String[] getPermission() {
    return new String[]{
        Manifest.permission.ACCESS_NETWORK_STATE,
        Manifest.permission.CHANGE_WIFI_STATE,
        Manifest.permission.ACCESS_WIFI_STATE,
        Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
        Manifest.permission.ACCESS_FINE_LOCATION
    };
  }

  @Override
  public void onPermissionRequestSuccess() {
    initNetty();
    initAction();
  }

  @Override
  public void onPermissionRequestFail() {

  }

  /**
   * 初始化空间设置
   */
  @SuppressLint("SetTextI18n")
  protected void initAction() {

    if (!WifiUtils.isWifiConnect()) { //无连接wifi
      WifiUtils.OpenWifi();
    }
    if (WifiUtils.isWifiConnect()) {//wifi已连接
      wifimTV.setText("已连接到" + WifiUtils.getSSID());
      mHost = WifiUtils.getWifiIP();
      System.out.println("======================================" + WifiUtils.getWifiIP());
    }

    if (WifiUtils.isWifiEnabled() && !WifiUtils.isWifiConnect()) {//wifi已开启，未连接
      wifimTV.setText("WiFi已开启，未连接");
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    requestPermission();

  }

  /**
   * 设置速度
   */
  private class myOnSeekChangeListener implements OnSeekChangeListener {

    @Override
    public void onSeeking(SeekParams seekParams) {

    }

    @Override
    public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
      String v = String.valueOf(seekBar.getProgress());
      mSettingTV.setText(v);
      sendNettyMsg("sensor {V5=" + v + "}\n");
    }
  }

  /**
   * 设置伸缩
   */
  private class myTleSeekbar implements OnSeekChangeListener {

    @Override
    public void onSeeking(SeekParams seekParams) {

    }

    @Override
    public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
      String trim = tvRot.getText().toString().trim();
      String v = String.valueOf(seekBar.getProgress());
//            tvTle.setText(v);
      sendNettyMsg("sensor {V6=" + v + "/" + trim + "}\n");
    }
  }


  /***
   * 设置转动
   */
  private class myRotSeekbar implements OnSeekChangeListener {

    @Override
    public void onSeeking(SeekParams seekParams) {

    }

    @Override
    public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
      String trim = tvTle.getText().toString().trim();
      String v = String.valueOf(seekBar.getProgress());
      sendNettyMsg("sensor {V6=" + trim + "/" + v + "}\n");
    }
  }

  /**
   * x轴
   */
  private class myXSeekbar implements OnSeekChangeListener {

    @Override
    public void onSeeking(SeekParams seekParams) {

    }

    @Override
    public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
      String v = String.valueOf(seekBar.getProgress());
      xTV.setText(v);
      ;
      String y = yTV.getText().toString().trim();
      String z = zTV.getText().toString().trim();
      sendNettyMsg("sensor {V8=" + v + "/" + y + "/" + z + "}\n");
    }
  }

  /**
   * Y轴
   */
  private class myYSeekbar implements OnSeekChangeListener {

    @Override
    public void onSeeking(SeekParams seekParams) {

    }

    @Override
    public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
      String x = xTV.getText().toString().trim();
      String v = String.valueOf(seekBar.getProgress());
      yTV.setText(v);
      ;
      String z = zTV.getText().toString().trim();
      sendNettyMsg("sensor {V8=" + x + "/" + v + "/" + z + "}\n");
    }
  }

  /**
   * Z轴
   */
  private class myZSeekbar implements OnSeekChangeListener {

    @Override
    public void onSeeking(SeekParams seekParams) {

    }

    @Override
    public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
      String x = xTV.getText().toString().trim();
      String y = yTV.getText().toString().trim();
      String v = String.valueOf(seekBar.getProgress());
      zTV.setText(v);
      ;
      sendNettyMsg("sensor {V8=" + x + "/" + y + "/" + v + "}\n");
    }
  }

  /**
   * 初始化Netty
   */
  private void initNetty() {
    mNetty = new ANetty(new Netty.OnChannelHandler() {
      @Override
      public void onMessageReceived(ChannelHandlerContext ctx, String msg) {
        //接收到消息
        Log.d(TAG, "on msg " + msg);
        String[] ms = msg.split("\n");
        for (String m : ms) {
          onSensorData(m);
        }
      }

      @Override
      public void onExceptionCaught(ChannelHandlerContext ctx, Throwable e) {

      }
    });
    mNetty.setOnConnectListener(new Netty.OnConnectListener() {
      @Override
      public void onSuccess() {
        //TODO 连接成功
        showToast("连接成功");

      }

      @Override
      public void onFailed() {
        //TODO 连接失败
        showToast("连接失败");
      }

      @Override
      public void onError(Exception e) {
        //TODO 连接异常
        showToast("连接异常");
        Log.e(ANetty.TAG, e.getMessage());
      }
    });

    mNetty.setOnSendMessageListener(new Netty.OnSendMessageListener() {
      @Override
      public void onSendMessage(Object msg, boolean success) {
        //发送消息
        if (!"sensor\n".equals(msg)) {
          if (success) {
            showToast("发送成功");
          } else {
            showToast("发送失败");
          }
        }
      }

      @Override
      public void onException(Throwable e) {
        //异常
        Log.e(ANetty.TAG, e.getMessage());
      }
    });
  }

  int ptocol = 0; // 0: 增加超声波之前的版本，1：兼容智慧城市协议版本

  // 解析收到的数据，获取当前水温值
  @SuppressLint("SetTextI18n")
  public void onSensorData(String data) {
    String trim = data.trim();
    int i = trim.indexOf(" ");
    if (i != -1) {
      trim = trim.substring(i + 1, trim.length());
    }
    if (trim.startsWith("{") && trim.endsWith("}")) {
      String var = trim.substring(1, trim.length() - 1); // 截取{}内的字符串
      // 数据格式 A0=25,A1=34.0
      String[] tags = var.split(","); // 以‘,’来分割字符串
      for (String tag : tags) { // 循环提取每项键值对，比如A0=25
        Log.e("TAG", "=====" + tag);
        String[] cv = tag.split("="); // 以‘=’来分割字符串
        if (cv[0].equals("A0")) { // 判断参数A0
          if (cv[1].contains("&")) {
            ptocol = 1;
          }
          if (ptocol == 0) {
            float v = Float.parseFloat(cv[1]);
            mTV0.setText("" + v);
          } else {
            String[] vs = cv[1].split("&");
            TextView[] tv = {mTV0/*光照*/, mTV4/*温度*/, mTV5/*湿度*/, mTV6/*气压*/, mTV2/*空气质量*/, mTV1/*燃气*/};
            if (vs.length == 6) {
              for (int k = 0; k < 6; k++) {
                float v = Float.parseFloat(vs[k]);
                tv[k].setText("" + v);
              }
            }
          }
        }
        if (cv[0].equals("A1")) { // 判断参数A0
          if (ptocol == 0) {
            float v = Float.parseFloat(cv[1]);
            mTV1.setText("" + v);
          } else {
            float v = Float.parseFloat(cv[1]); //电量
            mTV7.setText("" + v);
          }
        }
        if (cv[0].equals("A2")) { // 判断参数A0
          if (ptocol == 0) {
            float v = Float.parseFloat(cv[1]);
            mTV2.setText("" + v);
          }
        }
        if (cv[0].equals("A3")) { // 判断参数A0
          if (ptocol == 0) {
            float v = Float.parseFloat(cv[1]);
            mSpeedTV.setText("" + v);
          } else {
            /*超声波*/
            String[] vs = cv[1].split("&");
            TextView[] tv = {mTVRadar1, mTVRadar2, mTVRadar3, mTVRadar4};
            if (vs.length == 4) {
              for (int k = 0; k < 4; k++) {
                float v = Float.parseFloat(vs[k]);
                tv[k].setText("" + v);
              }
            }
          }
        }
        if (cv[0].equals("A4")) { // 判断参数A0
          if (ptocol == 0) {
            float v = Float.parseFloat(cv[1]);
            mTV4.setText("" + v);
          } else {
            /* 车速*/
            float v = Float.parseFloat(cv[1]);
            mSpeedTV.setText("" + v);
          }
        }
        if (cv[0].equals("A5")) { // 判断参数A0
          if (ptocol == 0) {
            float v = Float.parseFloat(cv[1]);
            mTV5.setText("" + v);
          }
        }
        if (cv[0].equals("A6")) { // 判断参数A0
          if (ptocol == 0) {
            float v = Float.parseFloat(cv[1]);
            mTV6.setText("" + v);
          }
        }
        if (cv[0].equals("A7")) { // 判断参数A0
          if (ptocol == 0) {
            float v = Float.parseFloat(cv[1]);
            mTV7.setText("" + v);
          }
        }

        if (cv[0].equals("V6")) { // 判断参数A0
          String[] vs = cv[1].split("/"); // 以‘,’来分割字符串
          if (vs.length == 2) {
            tvTle.setText(vs[0]);
            tvRot.setText(vs[1]);
          }
        }
      }
    }
  }

  /**
   * 连接Netty
   */
  private void connectNetty() {

//        mHost = etHost.getText().toString();
//        if(!TextUtils.isEmpty(etPort.getText())){
//            mPort = Integer.parseInt(etPort.getText().toString());
//        }
//
//        if(TextUtils.isEmpty(mHost)){
//            showToast("请配置TCP连接的主机");
//            return;
//        }
    //连接Netty
    mNetty.connect(mHost, mPort);
  }

  /**
   * 发送消息
   *
   * @param msg
   */
  private void sendNettyMsg(String msg) {
    if (mNetty.isConnected()) {
      mNetty.sendMessage(msg);
    } else {
      showToast("未连接小车");
    }

  }

  private void showToast(String text) {
    if (mToast == null) {
      mToast = Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT);
    }
    mToast.setText(text);
    mToast.show();

  }


  @Override
  protected void onDestroy() {
    mNetty.disconnect();
    super.onDestroy();
  }

  private String getDirection(RockerView.Direction direction) {
    String message = null;
    switch (direction) {
      case DIRECTION_UP:
        sendNettyMsg(Constants.V4[1]);
        message = "上";
        break;
      case DIRECTION_DOWN:
        sendNettyMsg(Constants.V4[2]);
        message = "下";
        break;
      case DIRECTION_LEFT:
        sendNettyMsg(Constants.V4[3]);
        message = "左";
        break;
      case DIRECTION_RIGHT:
        sendNettyMsg(Constants.V4[4]);
        message = "右";
        break;
      default:
        break;
    }
    return message;
  }

  @Override
  public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.igb_wifi:
//                connectNetty();
//                break;
//            case R.id.btn_check:
//                //sendNettyMsg(Constants.V2[1]);
//                sendNettyMsg("sc\n");
//
//                break;
//            case R.id.btn_grasp:
//                sendNettyMsg(Constants.V2[2]);
//                break;
//            case R.id.btn_release:
//                sendNettyMsg(Constants.V2[3]);
//                break;
//        }
  }

  void updateModeIcon(View v, int st) {
    View[] vs = new Button[]{mBtnModeControl, mBtnModeAuto, mBtnModeClour,

        mBtnModeSource, mBtnModeTrack, mBtnModeAvoidance,};
    int[] idOn = new int[]{R.drawable.main_control_on, R.drawable.code_on, R.drawable.main_colour_on,
        R.drawable.main_source_on, R.drawable.main_track_on, R.drawable.main_avoidance_on};
    int[] idOff = new int[]{R.drawable.main_control, R.drawable.code, R.drawable.main_colour,
        R.drawable.main_source, R.drawable.main_track, R.drawable.main_avoidance};
    for (int i = 0; i < 6; i++) {
      if (vs[i] == v) {
        if (st != 0) {
          v.setBackground(getDrawable(idOn[i]));
        } else {
          v.setBackground(getDrawable(idOff[i]));
        }
      }
    }
  }

  View.OnClickListener mOnModeClick = new View.OnClickListener() {
    View mLastView;

    public void onClick(View v) {
      if (mLastView != null) {
        updateModeIcon(mLastView, 0);
      }
      updateModeIcon(v, 1);
      mLastView = v;
      String cmd = null;
      if (v == mBtnModeControl) {
        cmd = "sensor {V1=0}\n";
      }
      if (v == mBtnModeAuto) {
        cmd = "sensor {V1=1}\n";
      }
      if (v == mBtnModeClour) {
        cmd = "sensor {V1=2}\n";
      }
      if (v == mBtnModeSource) {
        cmd = "sensor {V1=3}\n";
      }
      if (v == mBtnModeTrack) {
        cmd = "sensor {V1=4}\n";
      }
      if (v == mBtnModeAvoidance) {
        cmd = "sensor {V1=5}\n";
      }
      if (cmd != null) {
        sendNettyMsg(cmd);
      }
    }
  };
}
